package com.waimai.mobile.ui.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.waimai.mobile.R;
import com.waimai.mobile.api.WaiMaiServer;
import com.waimai.mobile.api.entity.ReceiveAddress;
import com.waimai.mobile.api.model.ResponseModel;
import com.waimai.mobile.ui.WaiMaiApp;
import com.waimai.mobile.ui.activity.AddressActivity_;
import com.waimai.mobile.ui.activity.AddressListActivity;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.App;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.EBean;
import org.androidannotations.annotations.RootContext;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.rest.RestService;

import java.util.List;

/**
 * Created by lin on 2015/6/20.
 */

@EBean
public class AddressItemAdapter extends BaseAdapter{

    @RootContext
    public AddressListActivity context;

    private boolean isChooseAddress = false;

    private int choosedAddressId;

    private OnChooseAddressListener onChooseAddressListener;

    private List<ReceiveAddress> addresses;

    private AlertDialog dialog;

    @App
    public WaiMaiApp app;

    @RestService
    public WaiMaiServer server;

    @Override
    public int getCount() {
        return addresses.size();
    }

    @Override
    public Object getItem(int position) {
        return getAddresses().get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        if(convertView == null){
            holder = new ViewHolder();
            convertView = LayoutInflater.from(context).inflate(R.layout.item_list_address, null);
            holder.isChoosedRBtn = (RadioButton) convertView.findViewById(R.id.isChoosedRBtn);
            holder.userNameTv = (TextView) convertView.findViewById(R.id.userNameTv);
            holder.phoneTv = (TextView) convertView.findViewById(R.id.phoneTv);
            holder.addressTv = (TextView) convertView.findViewById(R.id.addressTv);
            convertView.setTag(holder);
        }else{
            holder = (ViewHolder) convertView.getTag();
        }

        if(isChooseAddress){
            holder.isChoosedRBtn.setVisibility(View.VISIBLE);
            if(choosedAddressId == addresses.get(position).getAddressId()){
                holder.isChoosedRBtn.setChecked(true);
            }else{
                holder.isChoosedRBtn.setChecked(false);
            }
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    holder.isChoosedRBtn.setChecked(true);
                    if (onChooseAddressListener != null) {
                        onChooseAddressListener.onChoosedAddress(addresses.get(position));
                    }
                }
            });
        }else{
            holder.isChoosedRBtn.setVisibility(View.GONE);
        }

        if(addresses.get(position).getUserName() == null){
            holder.userNameTv.setVisibility(View.GONE);
        }else{
            holder.userNameTv.setText(addresses.get(position).getUserName());
            holder.userNameTv.setVisibility(View.VISIBLE);
        }
        holder.phoneTv.setText(addresses.get(position).getPhone());
        holder.addressTv.setText(addresses.get(position).getAddressName());

        convertView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                dialog = new AlertDialog.Builder(context)
                        .setItems(new String[]{"编辑", "删除"}, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch (which){
                                    case 0:
                                        Intent intent = new Intent(context, AddressActivity_.class);
                                        intent.putExtra("address", addresses.get(position));
                                        context.startActivity(intent);
                                        break;
                                    case 1:
                                        deleteAddress(app.getUser().getUserId(), addresses.get(position).getAddressId());
                                        break;
                                }
                            }
                        }).create();
                dialog.show();
                return true;
            }
        });

        return convertView;
    }

    @Background
    public void deleteAddress(Integer userId, Integer addressId){
        try {
            ResponseModel<ReceiveAddress> model = server.address(userId, addressId);
            if(model != null){
                switch (model.getStatus().getStatusCode()){
                    case ResponseModel.STATUS_REQUEST_SUCCESS:
                        reqeustSuccess();
                        break;
                    case ResponseModel.STATUS_REQUEST_FAILED:
                        reqeustFailed();
                        break;
                    case ResponseModel.STATUS_SERVER_ERROR:
                        serverError();
                }
            }else{
                serverError();
            }
        }catch (Exception e){
            e.printStackTrace();
            netError();
        }
    }

    @UiThread
    public void reqeustSuccess(){
        context.loadAddresses();
        Toast.makeText(context, "删除成功", Toast.LENGTH_SHORT).show();
    }

    @UiThread
    public void reqeustFailed(){
        Toast.makeText(context, "请求失败，请重试", Toast.LENGTH_SHORT).show();
    }

    @UiThread
    public void serverError(){
        Toast.makeText(context, "服务器错误，请重试", Toast.LENGTH_SHORT).show();
    }

    @UiThread
    public void netError(){
        Toast.makeText(context, "网络错误，请重试", Toast.LENGTH_SHORT).show();
    }


    public class ViewHolder{
        RadioButton isChoosedRBtn;
        TextView userNameTv;
        TextView phoneTv;
        TextView addressTv;
    }

    public interface OnChooseAddressListener{
        public void onChoosedAddress(ReceiveAddress address);
    }

    public boolean isChooseAddress() {
        return isChooseAddress;
    }

    public void setChooseAddress(boolean isChooseAddress) {
        this.isChooseAddress = isChooseAddress;
    }

    public List<ReceiveAddress> getAddresses() {
        return addresses;
    }

    public OnChooseAddressListener getOnChooseAddressListener() {
        return onChooseAddressListener;
    }

    public void setOnChooseAddressListener(OnChooseAddressListener onChooseAddressListener) {
        this.onChooseAddressListener = onChooseAddressListener;
    }

    public void setChooseedAddressId(int addressId){
        choosedAddressId = addressId;
    }

    public void setAddresses(List<ReceiveAddress> addresses) {
        this.addresses = addresses;
    }

}
